package com.gack.business.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gack.business.model.BusinessCardRecord;
import com.gack.business.model.Commodity;
import com.gack.business.model.Enterprise;
import com.gack.business.model.Invoice;
import com.gack.business.model.User;
import com.gack.business.repository.BusinessCardRecordRepository;
import com.gack.business.repository.CommodityRepository;
import com.gack.business.repository.EnterpriseRepository;
import com.gack.business.repository.InvoiceRepository;
import com.gack.business.repository.UserEnterpriseDepartmentPositionRepository;
import com.gack.business.repository.UserRepository;
import com.gack.helper.common.abstractobj.OrderIdhelper;
import com.gack.helper.common.config.PayConfig;
import com.gack.helper.common.util.HttpGetUtil;

@Service
public class BusinessCardRecordService implements BusinessCardRecordServiceInterface {

	@Autowired
	BusinessCardRecordRepository cardRepository;
	@Autowired
	UserRepository userRepository;
	@Autowired
	EnterpriseRepository enterpriseRepository;
	@Autowired
	CommodityRepository commodityRepository;
	@Autowired
	InvoiceRepository invoiceRepository;
	@Autowired
	OrderIdhelper idhelper;
	@Autowired
	UserEnterpriseDepartmentPositionRepository departmentPositionRepository;
	
	
	@Override
	public Map<String, String> save(String uid, String cid, String eid, int number,String channel,String back_url) {
		
		Map<String, String> map = new HashMap<>();
		map.put("state", "FAIL");
		User user = userRepository.findOne(uid);
		if(user != null) {
			Commodity commodity = commodityRepository.findOne(cid);
			if(commodity != null) {
				Enterprise enterprise = enterpriseRepository.findOne(eid);
				if(enterprise != null) {
					
					// 调用押金支付接口
					String baseUrl = PayConfig.PAY_URL;
					StringBuffer url = new StringBuffer();
					url.append(baseUrl).append("?uid=").append(user.getId()).append("&systemCode=").append("11")
							.append("&channel=").append(channel).append("&amount=").append(commodity.getSalePrice() * number).append("&business_card_type=")
							.append("6").append("&originalId=").append("DDCCBBAA")
							.append((back_url == null) ? "" :"&back_url=" + back_url);
					String result = HttpGetUtil.httpGet(url.toString());
					System.out.println(result);
					JSONObject parseObject = JSON.parseObject(result);
					map = JSON.toJavaObject(parseObject, Map.class);
					System.out.println(map);
					if (map.get("status") != null && "SUCCESS".equals(map.get("status"))){
						BusinessCardRecord cardRecord = new BusinessCardRecord();
						cardRecord.setUid(uid);
						cardRecord.setCid(cid);
						cardRecord.setEid(eid);
						cardRecord.setPlantid(idhelper.getBusinessId());
						cardRecord.setNumber(number);
						cardRecord.setAmount(commodity.getFaceValue() * number);
						cardRecord.setPayAmount(commodity.getSalePrice() * number);
						cardRecord.setOid(map.get("id").toString());
						cardRepository.save(cardRecord);
						map.put("state", "SUCCESS");
					}
					return map;
				} else {
					map.put("msg", "公司不存在");
				}
			} else { 
				map.put("msg", "商品不存在");
			}
		} else { 
			map.put("msg", "用户不存在");
		}
		return map;   
		    
	}

	@Override
	public boolean updateByOid(String oid) {
		BusinessCardRecord cardRecord = cardRepository.findByOid(oid);
		if(cardRecord != null && !cardRecord.getPay()) {
			// 保存商务卡购买记录
			cardRecord.setPay(true);
			cardRepository.save(cardRecord);
			Invoice invoice = new Invoice();
			invoice.setOid(cardRecord.getOid());
			invoice.setUid(cardRecord.getUid());
			invoice.setAmout(cardRecord.getAmount());
			invoice.setOrderTime(cardRecord.getCreateTime());
			invoice.setKind("1");
			// 商务卡余额添加
			Enterprise enterprise = enterpriseRepository.findOne(cardRecord.getEid());
			enterprise.setSurplusAmount(enterprise.getSurplusAmount() + cardRecord.getAmount());
			enterpriseRepository.save(enterprise);
			
			Commodity commodity = commodityRepository.findOne(cardRecord.getCid());
			// 添加销售数量
			commodity.setSalesAmount(commodity.getSalesAmount() + cardRecord.getNumber());
			commodityRepository.save(commodity);
			invoice.setName(commodity.getName());
			// 保存发票信息
			invoiceRepository.save(invoice);
			return true;
		}
		return false;  
	}

	@Override
	public Map<String, String> findEnterprisesIdsByUserId(String userId) {
		List<String> enterprises  = departmentPositionRepository.findEnterprisesIdsByUserId(userId);
		Map<String, String> map = new HashMap<>();
		enterpriseRepository.findAll(enterprises).forEach(e -> {
			map.put(e.getId(), e.getName());
		});
		return map;  
		    
	}
}
